from __future__ import annotations
import os
from .models import FileInfo

list_file_path = os.environ.get('download_list', None)
if not list_file_path:
    raise "Download File list path not set!"


def make_fid(name: str, size: int):
    res = size
    buffer = name.encode('utf8')
    for b in buffer:
        res *= b
    return res % (2**32-1)


class FileManager:
    file_dict: dict[int, FileInfo] = {}
    # need_save: bool = False
    # removed_set: set[int] = set()

    def __init__(self) -> None:
        self.file_dict = self.load_file_dict()

    def load_file_dict(self):
        valid_dict = {}
        invalid_line_count = 0
        if not os.path.exists(list_file_path):
            return valid_dict
        with open(list_file_path, encoding='utf8') as f:
            all_lines=f.readlines()
            # line_count = len(all_lines)
            normal_lines=set()
            removed_lines=set()
            for line in all_lines:
                line=line.strip()
                if line.startswith('-'):
                    removed_lines.add(line[1:])
                    invalid_line_count+=1
                else:
                    normal_lines.add(line)
            for path in normal_lines-removed_lines:
                if not os.path.isfile(path):
                    continue
                size = os.path.getsize(path)
                fid = make_fid(path, size)
                file_name = os.path.basename(path)
                valid_dict[fid] = FileInfo(
                    fid=fid, file_path=path, file_name=file_name, file_size=size)

        if invalid_line_count>100:
            print('Invalid line')
            self.rebulid_list_file(valid_dict.values())

        return valid_dict

    def rebulid_list_file(self, list: list[FileInfo]):
        print('Rebuild list file!')
        with open(list_file_path, 'w', encoding='utf8') as f:
            for fi in list:
                f.write(fi.file_path)
                f.write('\n')

    def remove_file(self, fid: int):
        path=self.get_file_path(fid)
        with open(list_file_path, 'a', encoding='utf8') as f:
            f.write(f'-{path}')
            f.write('\n')

        if fid not in self.file_dict:
            self.file_dict=self.load_file_dict()
            
        self.file_dict.pop(fid)


    def remove_all(self):
        with open(list_file_path, 'w', encoding='utf8') as f:
            pass
        self.file_dict.clear()

    def refresh_list(self):
        self.file_dict = self.load_file_dict()

    def get_file_path(self, fid: int):
        return self.file_dict[fid].file_path

    def get_file_list(self):
        return list(self.file_dict.values())



# def add_files(file_names: list[str], params):
#     if not FileManager.instance:
#         FileManager.instance = FileManager()
#     for file in file_names:
#         FileManager.instance.add_file(file)
